package org.limit.bookServe.utils;

import org.limit.bookServe.bean.Book;
import org.limit.bookServe.bean.User;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.limit.bookServe.utils.BaseClass.resourceReader;
import static org.limit.bookServe.utils.SystemConstants.BOOK_DATA_FILE_NAME;
import static org.limit.bookServe.utils.SystemConstants.USER_DATA_FILE_NAME;

/**
 * @author 1.
 * @version 1.0
 * @description: 系统数据存储类
 * @date 2023/11/4 20:39
 */
public class SystemData extends DataChannel {
    private static Map<String, User> users;
    private static List<Book> books;

    //加载系统数据
    public boolean loadingInfo() {
        if ((users = readData(resourceReader(USER_DATA_FILE_NAME))) == null
                || (books = readData(resourceReader(BOOK_DATA_FILE_NAME))) == null) {
            if (users == null) users = new HashMap<>();
            if (books == null) books = new ArrayList<>();
        }
        return true;
    }

    //保存系统用户数据
    public static boolean saveUserData() {
        return setData(users, resourceReader(USER_DATA_FILE_NAME));
    }
/*    public static boolean saveUserData() {
        System.out.println(users);
//        return setData(users, USER_DATA_FILE_NAME);
        return true;
    }*/

    //保存系统书籍数据
    public static boolean saveBooksData() {
        return setData(books, resourceReader(BOOK_DATA_FILE_NAME));
    }


    //替换缓存数据并持久化
    public static boolean saveBooksData2Root(List<Book> newBookList) {
        //修改缓存
        books = newBookList;
        return setData(books, resourceReader(BOOK_DATA_FILE_NAME));
    }


    public Map<String, User> getUsers() {
        return users;
    }

    public List<Book> getBooks() {
        return books;
    }
}




